const db = require('../db/index')
const jwt = require('jsonwebtoken')
const config = require('../config')
// 注册
exports.regest = (req, res) => {
  const userinfo = Object.assign(req.body, { is_delete: 0 });
  const selectSql = 'select * from bl_users where username=?'
  db.query(selectSql, userinfo.username, (err, result) => {
    if (err) return res.cc(err)
    if (result.length) return res.cc('此用户已存在')
    const insertSql = 'insert into bl_users  set ?'

    db.query(insertSql, userinfo, (err, result2) => {
      if (err) return res.cc(err);
      if (result2.affectedRows == 1) return res.cc('注册成功', 200);
      res.cc(result2);
    })
  })
}

exports.login = (req, res) => {
  const userinfo = req.body;
  const selectSql = 'select * from bl_users where username=?'
  db.query(selectSql, [userinfo.username], (err, result) => {
    if (err) return res.cc(err);
    if (result.length == 0 || result[0].is_delete == 1) return res.cc('此用户不存在');
    if (result[0].password != userinfo.password) return res.cc('密码不符合');
    const user = { ...result[0], password: null }
    const tokenStr = jwt.sign(user, config.secretKey, { expiresIn: config.expiresIn });
    const resultInfo = Object.assign(user, { token: tokenStr })
    res.cc('登录成功', 200, resultInfo);
  })

}